package com.hll.javaee.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class Session1 extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=utf-8");
    response.setCharacterEncoding("UTF-8");
    // session是存储在服务器上，相对于cookie能存放更多内容，一般存一次浏览中最常用的数据, 每个客户端(浏览器)有不同的session对象
    // session是自动创建的，只要访问了该网站的某个页面，就有
    // 后来我观察到会话创建时会有一个cookie{JSESSION,id}生成,当我们退出后,cookie消失,至于session底层原理还不知道
    // 可能cookie是session的辅助工具
    HttpSession session = request.getSession();
    if (session.getAttribute("name") == null)
      session.setAttribute("name", new Person("hll", 20)); // session可以存储对象以及其他更多对象
    String id = session.getId(); // 每个session有独一的id
    if (session.isNew()) { // 用户刚进入网站,会话刚生成
      response.getWriter().write("session 创建成功, id = " + id);
    } else {
      response.getWriter().write("session 已有, id = " + id);
    }
  }
}
